﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SocketClient
{
    public class Program
    {
        private static Socket Client;
        static void Main(string[] args)
        {
            Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Client.Connect("127.0.0.1", 8888);
            Console.WriteLine("已连接服务端，请注册昵称：");
            string name = Console.ReadLine();
            Client.Send(Encoding.UTF8.GetBytes(name));
            Thread th = new Thread(ReceiveMsg);
            th.Start();

            while (true) {
                string msg = Console.ReadLine();
                Client.Send(Encoding.UTF8.GetBytes(msg));
            }
        }

        static void ReceiveMsg()
        {
            byte[] buffer = new byte[1024];
            try
            {
                while (true)
                {
                    int num = Client.Receive(buffer);
                    if (num == 0) break;
                    string message = Encoding.UTF8.GetString(buffer, 0, num);
                    Console.WriteLine(message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Client.Close();
                Console.WriteLine("服务端已关闭");
            }
        }
    }
}
